package com.xj.socket.udp;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

/**
 * udp 服务器端和客户端没啥编码上的区别
 * User: bjxiajun
 * Date: 13-11-1
 * Time: 上午9:20
 */
public class Server {
    public static void start() throws Exception {
        InetAddress local=InetAddress.getByName("127.0.0.1");//socket 使用的本地地址
        DatagramSocket serverSocket=new DatagramSocket(6188,local);//创建服务器端 端口为6188 绑定的地址为127.0.0.0
        System.out.println("server start success ............");
        byte [] buffer=new byte[8*1024];
        DatagramPacket packet=new DatagramPacket(buffer,buffer.length);//接收客户端的包
        while(true){
            serverSocket.receive(packet);//等待客户端发送消息
            byte []data= packet.getData();
            System.out.println(new String(data,0,packet.getLength(),"UTF-8"));
            System.out.println("client port:"+packet.getPort());
            byte [] sendPacket="OK".getBytes();
            serverSocket.send(new DatagramPacket(sendPacket,sendPacket.length,packet.getAddress(),
                    packet.getPort()));//使用客户端的ip,port 进行回复
        }
    }

    public static void main(String[] args) throws Exception {
        Server.start();
    }
}
